/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.dao;

import java.util.ArrayList;
import java.util.Date;
import mill.hibernate.dto.DeliveryInstruction_mill;
import mill.hibernate.dto.QualityReport_mill;
import mill.hibernate.dto.WeightNoteRef_mill;
import mill.hibernate.dto.WeightNote_mill;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import trader.hibernate.dto.*;
import wstrader.util.Common;

/**
 *
 * @author kiendn
 */
public class DeliveryInstructionMillDao {

    private Session session = null;

    public DeliveryInstructionMillDao() {
        SessionFactory sf = MillHibernateUtil.getSessionFactory();
        session = sf.openSession();
    }

    public DeliveryInstruction_mill getDI(int id) {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(DeliveryInstruction_mill.class);
            crit.add(Restrictions.eq("id", id));
            DeliveryInstruction_mill di = (DeliveryInstruction_mill) crit.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();

            return di;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        //return false;
        return null;
    }

    public boolean update_di(DeliveryInstruction_mill di) {
        try {
            session.getTransaction().begin();
            session.update(di);
            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();

            return true;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        //return false;
        return false;
    }

    public String getNewRef() {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(DeliveryInstruction_mill.class);

            crit.setProjection(Projections.max("refNumber"));
            String ref = (String) crit.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();

            return getNextRefNumber(ref);

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        //return false;
        return "";
    }

    public String getNextRefNumber(String ref_number) {
        String result = "";
        String[] new_string = ref_number.split("-");
        if (new_string.length == 5) {
            int n = Integer.parseInt(new_string[4]);
            int lengthOfNum = ("" + (n + 1)).length();
            switch (lengthOfNum) {
                case 1:
                    new_string[4] = "0000" + (n + 1);
                    break;
                case 2:
                    new_string[4] = "000" + (n + 1);
                    break;
                case 3:
                    new_string[4] = "00" + (n + 1);
                    break;
                case 4:
                    new_string[4] = "0" + (n + 1);
                    break;
                case 5:
                    new_string[4] = "" + (n + 1);
                    break;
                default:
                    new_string[4] = "" + (n + 1);
            }
            result = new_string[0] + "-" + new_string[1] + "-" + new_string[2] + "-" + new_string[3] + "-" + new_string[4];
        }
        return result;
    }

    public int save_mill_DI(DeliveryInstruction_mill di) {

        try {

            int new_id = getNewDI_id();
            di.setId(new_id);

            session.getTransaction().begin();

            session.save(di);

            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();

            return new_id;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return -1;
    }

    private int getNewDI_id() {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(DeliveryInstruction_mill.class);

            crit.setProjection(Projections.max("id"));
            int new_id = (Integer) crit.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();

            return (new_id + 1);

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return -1;
    }

    public boolean updateDI(DeliveryInstruction_mill di_mill) {
        try {
            session.getTransaction().begin();

            session.update(di_mill);
            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();
            return true;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return false;
    }

    public ArrayList<WeightNote_mill> get_wn_by_di_id(int mill_id) {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(WeightNote_mill.class);
            crit.add(Restrictions.eq("instId", mill_id));

            ArrayList<WeightNote_mill> list = (ArrayList<WeightNote_mill>) crit.list();

            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();
            return list;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public QualityReport_mill get_qr(int qr_id) {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(QualityReport_mill.class);
            crit.add(Restrictions.eq("id", qr_id));

            QualityReport_mill qr = (QualityReport_mill) crit.uniqueResult();

            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();
            return qr;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public ArrayList<WeightNoteRef_mill> get_wnr(int wn_id) {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(WeightNote_mill.class);
            crit.add(Restrictions.eq("wn_id", wn_id));

            ArrayList<WeightNoteRef_mill> list = (ArrayList<WeightNoteRef_mill>) crit.list();

            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();
            return list;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public ArrayList<DeliveryInstruction_mill> getAllDI() {
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(DeliveryInstruction_mill.class);
            //crit.add(Restrictions.eq("wn_id", wn_id));

            ArrayList<DeliveryInstruction_mill> list = (ArrayList<DeliveryInstruction_mill>) crit.list();

            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();
            return list;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public WeightNote getWNfromMill(WeightNote_mill wn_mill) {
        String refNumber = wn_mill.getRefNumber();
        Character type = wn_mill.getType();
        Date date = wn_mill.getDate();
        Date time = wn_mill.getTime();
        Integer instId = wn_mill.getInstId();
        String truckNo = wn_mill.getTruckNo();
        String driver = wn_mill.getDriver();
        String area = wn_mill.getArea();
        Short gradeId = wn_mill.getGradeId();
        Float grossWeight = wn_mill.getGrossWeight() / 1000;
        Float tareWeight = wn_mill.getTareWeight() / 1000;
        Float netWeight = wn_mill.getNetWeight() / 1000;
        Short noOfBags = wn_mill.getNoOfBags();
        Byte packingId = wn_mill.getPackingId();
        Integer wrcId = wn_mill.getWrcId();
        Integer qrId = wn_mill.getQrId();
        Short userId = 19;
        Byte status = wn_mill.getStatus();
        Short allocatedBags = wn_mill.getAllocatedBags();
        Float allocatedWeight = wn_mill.getAllocatedWeight()/1000;
        Float stockWeight = wn_mill.getStockWeight()/1000;
        Short stockBags = wn_mill.getStockBags();

        return new WeightNote(refNumber, type, date, time, instId, truckNo, driver, area, gradeId, grossWeight, tareWeight, netWeight, noOfBags, packingId, wrcId, qrId, userId, status, allocatedBags, allocatedWeight, stockWeight, stockBags);
    }

    public QualityReport getQRfromMill(QualityReport_mill qr_mill) {
        
        Character type = qr_mill.getType();
        String refNumber = qr_mill.getRefNumber();
        Date qr_date = qr_mill.getDate();
        Date qr_time = qr_mill.getTime();
        Byte qr_status = qr_mill.getStatus();
        Float aboveSc20 = qr_mill.getAboveSc20();
        Float sc20 = qr_mill.getSc20();
        Float sc19 = qr_mill.getSc19();
        Float sc18 = qr_mill.getSc18();
        Float sc17 = qr_mill.getSc17();
        Float sc16 = qr_mill.getSc16();
        Float sc15 = qr_mill.getSc15();
        Float sc14 = qr_mill.getSc14();
        Float sc13 = qr_mill.getSc13();
        Float sc12 = qr_mill.getSc12();
        Float belowSc12 = qr_mill.getBelowSc12();
        Float black = qr_mill.getBlack();
        Float broken = qr_mill.getBroken();
        Float blackBroken = qr_mill.getBlackBroken();
        Float brown = qr_mill.getBrown();
        Float moisture = qr_mill.getMoisture();
        Float oldCrop = qr_mill.getOldCrop();
        Float excelsa = qr_mill.getExcelsa();
        Float floater = qr_mill.getFloater();
        Float foreignMatter = qr_mill.getForeignMatter();
        Float worm = qr_mill.getWorm();
        Float moldy = qr_mill.getMoldy();
        String cupClass = qr_mill.getCupClass();
        Integer sampleDtsId = qr_mill.getSampleDtsId();
        String qr_remark = qr_mill.getRemark();
        Short qr_userId = 19;
        Date completedDate = qr_mill.getCompletedDate();

        return new QualityReport(type, refNumber, qr_date, qr_time, qr_status, aboveSc20, sc20, sc19, sc18, sc17, sc16, sc15, sc14, sc13, sc12, belowSc12, black, broken, blackBroken, brown, moisture, oldCrop, excelsa, floater, foreignMatter, worm, moldy, cupClass, sampleDtsId, qr_remark, qr_userId, completedDate);
    }

    public static void main(String[] args) {
        DeliveryInstructionMillDao dao = new DeliveryInstructionMillDao();
//        String new_ref = dao.getNewRef();
//        int new_id = dao.getNewDI_id();
        //ArrayList<DeliveryInstruction_mill> list = dao.getAllDI();
        /*for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).getId() + "-" + list.get(i).getBuyerRef());
            int contract_id = new DeliveryInstructionDao().getContractId(list.get(i).getBuyerRef());
            if (contract_id > 0) {

                Date date = list.get(i).getDate();
                Date time = list.get(i).getTime();
                //Integer contractId = 0;
                Short supplierId = list.get(i).getSupplierId();
                String supplierRef = list.get(i).getSupplierRef();
                Short buyerId = list.get(i).getBuyerId(); //SW Commodities
                String buyerRef = list.get(i).getBuyerRef();
                Date deliveryDate = list.get(i).getDeliveryDate();
                Date fromTime = list.get(i).getFromTime();
                Date toTime = list.get(i).getToTime();
                Short gradeId = list.get(i).getGradeId();
                Double tons = list.get(i).getTons();
                Short packingId = list.get(i).getPackingId();
                Float kgPerBag = list.get(i).getKgPerBag();
                Short noOfBags = list.get(i).getNoOfBags();
                Short deliveredBags = list.get(i).getDeliveredBags(); // don't know, just leave it zero (by kiendn 6/11)
                Byte warehouseId = list.get(i).getWarehouseId();
                String markingOnBags = list.get(i).getMarkingOnBags();//can't find where it is (by kiendn 6/11)
                Short weightControllerId = list.get(i).getWeightControllerId();
                Short qualityControllerId = list.get(i).getQualityControllerId();
                Short originId = list.get(i).getOriginId();
                Short userId = 19; // stand for trade.
                Byte status = list.get(i).getStatus();
                String description = list.get(i).getDescription();
                String remark = list.get(i).getRemark();
                Short a = 0;
                String new_ref = new DeliveryInstructionDao().getNewDIRef();

                DeliveryInstruction trader_di = new DeliveryInstruction(new_ref, date, time, contract_id, supplierId, supplierRef, buyerId, buyerRef, deliveryDate, fromTime, toTime, gradeId, tons, packingId, kgPerBag, noOfBags, deliveredBags, warehouseId, markingOnBags, a, a, a, weightControllerId, qualityControllerId, userId, status, description, remark);

                int inst_id = new DeliveryInstructionDao().saveDI(trader_di);

                new DeliveryInstructionDao().save_to_mediate(new TraderdiMilldi(inst_id, list.get(i).getId(), warehouseId));
                
                ArrayList<WeightNote_mill> wn_list = new DeliveryInstructionMillDao().get_wn_by_di_id(list.get(i).getId());
                for (int j = 0; j < wn_list.size(); j++) {

                    //String new_wn_ref = 
                    QualityReport_mill qr_mill = new DeliveryInstructionMillDao().get_qr(wn_list.get(j).getQrId());

                    qr_mill.setRefNumber(new DeliveryInstructionDao().getNewQrRef());

                    Character type = qr_mill.getType();
                    String refNumber = qr_mill.getRefNumber();
                    Date qr_date = qr_mill.getDate();
                    Date qr_time = qr_mill.getTime();
                    Byte qr_status = qr_mill.getStatus();
                    Float aboveSc20 = qr_mill.getAboveSc20();
                    Float sc20 = qr_mill.getSc20();
                    Float sc19 = qr_mill.getSc19();
                    Float sc18 = qr_mill.getSc18();
                    Float sc17 = qr_mill.getSc17();
                    Float sc16 = qr_mill.getSc16();
                    Float sc15 = qr_mill.getSc15();
                    Float sc14 = qr_mill.getSc14();
                    Float sc13 = qr_mill.getSc13();
                    Float sc12 = qr_mill.getSc12();
                    Float belowSc12 = qr_mill.getBelowSc12();
                    Float black = qr_mill.getBlack();
                    Float broken = qr_mill.getBroken();
                    Float blackBroken = qr_mill.getBlackBroken();
                    Float brown = qr_mill.getBrown();
                    Float moisture = qr_mill.getMoisture();
                    Float oldCrop = qr_mill.getOldCrop();
                    Float excelsa = qr_mill.getExcelsa();
                    Float floater = qr_mill.getFloater();
                    Float foreignMatter = qr_mill.getForeignMatter();
                    Float worm = qr_mill.getWorm();
                    Float moldy = qr_mill.getMoldy();
                    String cupClass = qr_mill.getCupClass();
                    Integer sampleDtsId = qr_mill.getSampleDtsId();
                    String qr_remark = qr_mill.getRemark();
                    Short qr_userId = 19;
                    Date completedDate = qr_mill.getCompletedDate();

                    QualityReport qr = new QualityReport(type, refNumber, qr_date, qr_time, qr_status, aboveSc20, sc20, sc19, sc18, sc17, sc16, sc15, sc14, sc13, sc12, belowSc12, black, broken, blackBroken, brown, moisture, oldCrop, excelsa, floater, foreignMatter, worm, moldy, cupClass, sampleDtsId, qr_remark, qr_userId, completedDate);

                    int qr_id = new DeliveryInstructionDao().saveQr(qr);                   
                    
                    if (qr_id > 0) {
                        wn_list.get(j).setQrId(qr_id);
                    }

                    wn_list.get(j).setRefNumber(new DeliveryInstructionDao().getNewWnRef());

                    WeightNote wn = new DeliveryInstructionMillDao().getWNfromMill(wn_list.get(j));

                    wn.setInstId(inst_id);

                    DeliveryInstructionDao trader_dao = new DeliveryInstructionDao();

                    int new_wn_id = trader_dao.saveWn(wn);
                    
                    boolean new_dt = new DeliveryInstructionDao().save_to_QrWn(new Mediate(qr_id, qr_mill.getId(), "QR", warehouseId));
                    new_dt = new DeliveryInstructionDao().save_to_QrWn(new Mediate(new_wn_id, wn_list.get(j).getId(), "WN", warehouseId));
                }
            }
        }*/
        
        DeliveryInstructionDao di_dao = new DeliveryInstructionDao();
        
        ArrayList<Contracts> contract_list = di_dao.getPurchaseContracts();
        
        SessionFactory sf = MillHibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        
        try {
            session.getTransaction().begin();

            Criteria crit = session.createCriteria(DeliveryInstruction_mill.class);
            //crit.add(Restrictions.eq("wn_id", wn_id));

            ArrayList<DeliveryInstruction_mill> list = (ArrayList<DeliveryInstruction_mill>) crit.list();
            
            for (int i = 0; i < list.size(); i++){
                list.get(i).setBuyerRef(contract_list.get(i).getRefNumber());
                list.get(i).setSupplierRef(contract_list.get(i).getRefNumber());
            }

            session.flush();
            session.getTransaction().commit();
            //DeliveryInstruction_mill DI = (DeliveryInstruction_mill)crit.uniqueResult();
            //return list;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        //return null;

    }
}
